<template>
  <div class="invite-comp">
    <div class="box">
      <div class="row">
        <div class="label" style="width: 70px">邀请码</div>
        <div class="value flex-1">
          <n-input
            placeholder="请输入/设置邀请码"
            v-model:value="model.code"
          ></n-input>
        </div>
      </div>

      <div class="row">
        <div class="label" style="width: 70px">使用次数</div>
        <div class="value flex-1">
          <n-input-number
            :min="1"
            placeholder="请输入使用次数"
            v-model:value="model.maxNum"
          ></n-input-number>
        </div>
      </div>
    </div>

    <div class="flex flex-center mt-15">
      <n-button
        class="submit-btn"
        type="primary"
        :loading="loading1"
        @click="addInviteCode"
      >
        保存
      </n-button>
    </div>

    <!-- 邀请码记录 -->
    <div style="height: 300px">
      <div class="cl-basic mt-15 mb-15">邀请码记录</div>
      <n-skeleton text :repeat="3" v-if="loading2"></n-skeleton>
      <ScrollView class="box" style="height: 265px" v-else-if="codeList.length">
        <div class="row" v-for="(v, i) in codeList" :key="i">
          <div class="label">{{ v.code }}</div>
          <div class="value">{{ v.useNum }}/{{ v.maxNum }}次</div>
        </div>
      </ScrollView>
      <n-empty class="mt-30" description="暂无数据" v-else></n-empty>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import api from '@/kang/js/api'

const model = ref({
  code: null,
  maxNum: null,
})

const codeList = ref([])
const loading1 = ref(false)
const loading2 = ref(false)

getInviteCodeList()

// 获取邀请码记录
async function getInviteCodeList() {
  try {
    const params = {
      current: 1,
      pageSize: 10000,
    }

    loading2.value = true
    const { code, data } = await api.getInviteCodeList(params)
    loading2.value = false

    if (code === 200) {
      codeList.value = data.list || []
    }
  } catch (err) {
    loading2.value = false
  }
}

// 新增邀请码
async function addInviteCode() {
  try {
    const params = {
      ...model.value,
    }

    loading1.value = true
    const { code } = await api.addInviteCode(params)
    loading1.value = false

    if (code === 200) {
      model.value.code = null
      model.value.maxNum = null
      $message.success('新增成功')
      getInviteCodeList()
    }
  } catch (err) {
    loading1.value = false
  }
}
</script>

<style lang="scss" scoped>
.invite-comp {
  .box {
    border-radius: 12px;
    background-color: white;

    .row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;

      .value {
        color: var(--color-basic);
        font-size: 13px;
      }

      &:not(:last-child) {
        border-bottom: 1px solid var(--color-border);
      }
    }
  }

  :deep(.n-input) {
    .n-input__border {
      display: none;
    }
  }
}
</style>
